package com.example.wto.myapplication;

import android.os.Environment;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wto on 4/15/2017.
 */

public class ParseHtml
{
    private String cookie = "";
    public int CODE_ERROR=0;
    private final static String WEEK[]={"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
    public Teacher getTeacher(String tid,String teaid,String code)
    {
        Map<Integer, List<Course>> cmap = sendPost(tid, teaid, code);

        int j=0;
        Teacher teacher =new Teacher(tid,teaid,"王兴");
        teacher.getWeekList().clear();
        if (cmap != null)
        {
            for (Map.Entry<Integer, List<Course>> l : cmap.entrySet()) {
                System.out.println(WEEK[j]);
                if(j>=7)
                {
                    break;
                }


                DayOfWeek weekDay=new DayOfWeek(WEEK[j]);
                weekDay.setCourseList(l.getValue());
                teacher.getWeekList().add(weekDay);
                j++;
            }

            return teacher;
        }
        else
        {
            return null;
        }
    }
    public List<TermBean> getIndex() {
        try {
            URL url = new URL("http://jwweb.fjny.edu.cn:8081/ZNPK/TeacherKBFB.aspx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            Map<String, List<String>> map = conn.getHeaderFields();
            cookie = map.get("Set-Cookie").get(0);
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in,"gbk"));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            String index = builder.toString();
            reader.close();
            conn.disconnect();

            Document doc = Jsoup.parse(index);
            Elements elements = doc.select("select[name=\"Sel_XNXQ\"] option");
            List<TermBean> termList = new ArrayList<TermBean>();
            for (Element element : elements) {
                String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
                TermBean termBean=new TermBean(element.val(),element.html());
                termList.add(termBean);
            }

            return termList;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    // ???????? ????? ??? ?????????
    public Map<Integer, List<Course>> sendPost(String termId, String tid, String code) {
        try {
            URL url = new URL("http://jwweb.fjny.edu.cn:8081/ZNPK/TeacherKBFB_rpt.aspx");
            String param = "Sel_XNXQ=" + termId + "&Sel_JS=" + tid + "&type=" + 1 + "&txt_yzm=" + code;
            // Connection con =
            // Jsoup.connect("http://jwweb.fjny.edu.cn:8081/ZNPK/TeacherKBFB_rpt.aspx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36");
            conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
            conn.setRequestProperty("Referer", "http://jwweb.fjny.edu.cn:8081/ZNPK/TeacherKBFB.aspx");
            conn.setRequestProperty("Origin", "http://jwweb.fjny.edu.cn:8081");
            conn.setRequestProperty("Cache-Control", "max-age=0");

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(param);
            dos.flush();
            dos.close();

            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in,"gbk"));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            String info = builder.toString();
            if(info.contains("验证码错误"))
            {
                CODE_ERROR=1;
                return null;
            }
            Document doc = Jsoup.parse(info);
            Elements elements = doc.select("td");
            elements.get(0);

            Map<Integer, List<Course>> cmap = new LinkedHashMap<>();

            List<Course> cl1 = new ArrayList<Course>();
            List<Course> cl2 = new ArrayList<Course>();
            List<Course> cl3 = new ArrayList<Course>();
            List<Course> cl4 = new ArrayList<Course>();
            List<Course> cl5 = new ArrayList<Course>();
            List<Course> cl6 = new ArrayList<Course>();
            List<Course> cl7 = new ArrayList<Course>();

            cmap.put(1, cl1);
            cmap.put(2, cl2);
            cmap.put(3, cl3);
            cmap.put(4, cl4);
            cmap.put(5, cl5);
            cmap.put(6, cl6);
            cmap.put(7, cl7);

            for (Element week : elements) {
                if (week.html().equals("星期一")) {
                    Element wtr = week.parent();
                    Elements trs = wtr.siblingElements();
                    for (int j = 0; j < trs.size(); j++) {
                        Element tr = trs.get(j);
                        Elements trds = tr.children();
                        int ncounter = 0;
                        for (int i = 0; i < trds.size(); i++) {
                            Element td = trds.get(i);

                            if (td.attr("valign").equals("top")) {
                                if (td.text() != null)
                                    cmap.get(i - ncounter + 1).add(new Course(td.text() + ""));
                                else
                                    cmap.get(i - ncounter + 1).add(new Course(""));
                            } else
                                ncounter++;
                        }
                    }
                    CODE_ERROR=0;
                    return cmap;
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CODE_ERROR=0;
        return null;

    }

    public int getImage() {
        //
        FileOutputStream fo=null;
        InputStream in=null;
        HttpURLConnection conn=null;
        try {
            URL url = new URL("http://jwweb.fjny.edu.cn:8081/sys/ValidateCode.aspx");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Referer", "http://jwweb.fjny.edu.cn:8081/ZNPK/TeacherKBFB.aspx");
             in = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(),"codeImage.jpg");
            if (!file.exists()) {
                file.createNewFile();
            }
            fo = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = in.read(buf, 0, buf.length)) != -1) {
                fo.write(buf, 0, length);
            }
            return 1;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            try
            {
                in.close();
                fo.close();
                conn.disconnect();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return -1;
    }



    // ?????????
    public List<TeacherBean> getTeachers(String term) {
        try {
            URL url = new URL("http://jwweb.fjny.edu.cn:8081/ZNPK/Private/List_JS.aspx?xnxq=" + term + "&t=276");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in,"gbk"));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            String info = builder.toString();

            reader.close();
            conn.disconnect();

            Document doc = Jsoup.parse(info);
            doc = Jsoup.parse(doc.select("script").html().substring(24));
            Elements eles = doc.select("select[name=\"Sel_JS\"] option");
            List<TeacherBean> slist = new ArrayList<>();
            for (Element element : eles) {
                String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
               // slist.add(t);
                TeacherBean teacherBean=new TeacherBean(element.val(),element.html());
                slist.add(teacherBean);
                // System.out.println(t);
            }

            return slist;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static String string2Unicode(String string) {

        StringBuffer unicode = new StringBuffer();

        for (int i = 0; i < string.length(); i++) {

            // ??????????
            char c = string.charAt(i);

            // ????unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }

        return unicode.toString();
    }

    public String getCookie()
    {
        return cookie;
    }

    public void setCookie(String cookie)
    {
        this.cookie = cookie;
    }
}
